<template>
	<view class="loginAndRegister safety  savebottom">
		<view class="forgetText">
			<text>欢迎使用逆伶生物</text>
			<text>Welcome to the niling</text>
		</view>
		<view class="logoBigBox" v-if="isLogin">
			<view style="margin-bottom: 40rpx;width: 60%;">
				<view class="between btnBigBox">
					<view :class="[{'activeText':tabIndex==i}]" style="width: 400rpx;" v-for="(item,i) in tabList" @click="onChangeBtn(i)" :key="i">
						{{item}}
						<view :class="[{'activeColor':tabIndex==i},'line']" style="width: 60rpx;"></view>
					</view>
				</view>
			</view>
			<input class="input" style="" type="tel" v-model="account" placeholder="请输入手机号"></input>
			<view class="passwordBigBox">
				<input style="width: 93%;" v-show="tabIndex==0" class="input" v-model="password" placeholder="请输入密码" :type="inputType">
				<view class="eyeIcon" @click.stop="cheakPassword" v-show="tabIndex==0">
					<uni-icons v-show="inputType=='password'" type="eye-slash" size="25"></uni-icons>
					<uni-icons v-show="inputType=='text'" type="eye" size="25"></uni-icons>
				</view>
			</view>
			<view class="codeBox" v-if="tabIndex==1">
				<input class="input" v-model="yzm" placeholder="请输入验证码"></input>
				<view class="cardBtn flex-center" @click="onGetVerificationCode()">
					<text>
						{{isSend ? `${time} S` : "获取验证码"}}
					</text>
				</view>
			</view>
			<view class="checkBigBox flex-start">
				<checkbox-group @change="selectIsCheckedSaveUser">
					<checkbox :checked="isCheckedSaveUser" value="agree">
						<text style="color: #B3B3B3;" @click.stop="">记住密码？</text>
					</checkbox>
				</checkbox-group>
			</view>
			<view class="checkBigBox" style="display: flex; flex-direction: row; align-items: center;">
				<checkbox-group @change="selectBox">
					<checkbox :checked="isChecked" value="agree">
						<text style="color: #B3B3B3;" @click.stop="">我已阅读并同意</text>
					</checkbox>
				</checkbox-group>
				<text @click.stop="onSkip('/package/mine/agreement?pageType=平台用户协议')">《用户协议》</text>和<text @click.stop="onSkip('/package/mine/agreement?pageType=隐私政策')">《隐私协议》</text>
			</view>
			<view class="submitBtn flex" @click="onClickLogin()">登录</view>
			<view class="between">
				<view class="flex-center forget" @click="onSkip(`/pages/login/sybForgetPassword?type=1&choujiang=${choujiang}&bid=${bid}&yqcode=${yqcode}&isWebpage=true`)">
					注册新用户</view>
				<view class="flex-center forget" style="color:#333333 ;" @click="onSkip('/pages/login/forgetPassword?type=0')">忘记密码?</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		login,
		reqLoginStatus,
		getPersonalCenter,
		getVerificationCode
	} from "../../api/index.js"
	import {
		getConfigJson
	} from "api/appapi.js"
	export default {
		data() {
			return {
				isLogin: false,
				isRestart: false,
				visitorId: '',
				inputType: 'password',
				isChecked: true,
				isCheckedSaveUser: true,
				tabList: ['密码登录', '验证码登录'],
				tabIndex: 0,
				isHide: true,
				account: '',
				password: '',
				yzm: "",
				isSend: false,
				time: 60,
				choujiang: null, //是否有抽奖,大于0就有,
				bid: "",
				yqcode: ""
			}
		},
		onLoad(option) {
			this.choujiang = option.choujiang;
			this.bid = option.bid ? option.bid : '';
			this.yqcode = option.yqcode;
			var saveUser = uni.getStorageSync('saveUser');
			if (saveUser && saveUser.account) {
				this.account = saveUser.account;
			}

			if (saveUser && saveUser.password) {
				this.password = saveUser.password
			}

			uni.setStorageSync('choujiang', option.choujiang)
			uni.setStorageSync('bid', option.bid)

			const fpPromise = import('./fingerprintjsv4.js')
				.then(FingerprintJS => FingerprintJS.load())
			fpPromise.then(fp => fp.get()).then(result => {
				const visitorId = result.visitorId
				this.visitorId = visitorId;

				if (saveUser && saveUser.account && saveUser.password) {
					uni.showLoading({
						title: '请求支付中...'
					})
					setTimeout(() => {
						this.onLogin();
					}, 1000);
				} else {
					uni.showLoading({
						title: '请求支付中...'
					})
					this.onLogin();
				}
			})
		},
		onShow() {
			if (!this.isRestart) {
				//this.onReqLoginStatus()
			}
		},
		methods: {
			cheakPassword() {
				this.inputType == 'text' ? this.inputType = 'password' : this.inputType = 'text'
			},
			// 勾选用户协议
			selectBox(e) {
				console.log(e, "eeee")
				e.detail.value.length != 0 ? this.isChecked = true : this.isChecked = false
				console.log(this.isChecked, "***")
			},
			// 勾选用户协议
			selectIsCheckedSaveUser(e) {
				console.log(e, "eeee")
				e.detail.value.length != 0 ? this.isCheckedSaveUser = true : this.isCheckedSaveUser = false
				console.log(this.isCheckedSaveUser, "***")
			},
			// 清除登录态
			async onReqLoginStatus() {
				const res = await reqLoginStatus('s=/ApiIndex/logindata')

				const {
					status,
					msg
				} = res.data
				if (status != 1) {
					this.showToast(msg)
				}

				uni.setStorageSync('sessionData', {
					account: '',
					session_id: '',
					socket_token: ''
				})
			},
			async onLogin() {
				const {
					account,
					password,
					tabIndex,
					visitorId,
					yzm
				} = this
				const QRSession = uni.getStorageSync('qrSession')
				console.log(QRSession, "QRSession")

				let logintype = 1;
				if (account && password) {
					logintype = tabIndex + 1;
				} else {
					logintype = 3;
				}

				const res = await login(
					`s=/ApiIndex/sybpaylogin&bid=${this.bid}&tel=${account}&pwd=${password}&visitorid=${visitorId}&logintype=${logintype}&pid=0&smscode=${yzm}&session_id=${QRSession}`
				)
				const {
					session_id,
					socket_token,
					status,
					payurl,
					msg
				} = res.data

				if (this.isCheckedSaveUser) {
					uni.setStorageSync('saveUser', {
						account: account,
						password: password
					})
				}
				if (logintype != 3) {
					this.showToast(msg)
				}
				uni.hideLoading();
				if (status == 1) {
					uni.setStorageSync('sessionData', {
						account: account,
						session_id: session_id,
						socket_token: socket_token
					})

					const sessionData = uni.getStorageSync('sessionData')
					let isLogin = '.anon';

					if (sessionData && sessionData.session_id) {
						isLogin = '';
					}

					let globalData = getApp().globalData;

					var BASE_URL = globalData.BASE_URL;
					var platform = 'app';
					const isAgency = globalData.isAgency;

					// #ifdef H5
					platform = 'h5'
					if (isAgency) {
						BASE_URL = '/api'
					}
					// #endif


					const testAccountRes = await getConfigJson(
						`${BASE_URL}/app/config/config.test.account.json`)

					const testAccountData = testAccountRes.data

					if (testAccountData.status == 1) {
						uni.setStorageSync('TESTACCOUNT', JSON.stringify(testAccountData.data));
					}

					console.log(testAccountData)

					if (account) {
						if (testAccountData.data.indexOf(account) >= 0) {
							isLogin = '.anon';
						}
					}

					const res = await getConfigJson(
						`${BASE_URL}/app/config/config.${globalData.channelVersionNumber}${isLogin}.json`)
					const {
						data,
						status,
						msg
					} = res.data

					if (status == 1) {

						globalData.config = data;
						console.log("保存APP配置")
						uni.setStorageSync('APPCONFIG', JSON.stringify(data));

						if (!data.isTabbar1) {
							uni.setTabBarItem({
								index: 0,
								visible: false
							})
						}

						if (!data.isTabbar2) {
							uni.setTabBarItem({
								index: 1,
								visible: false
							})
						}

						if (!data.isTabbar3) {
							uni.setTabBarItem({
								index: 2,
								visible: false
							})
						}

						if (!data.isTabbar4) {
							uni.setTabBarItem({
								index: 3,
								visible: false
							})
						}

						if (!data.isTabbar5) {
							uni.setTabBarItem({
								index: 4,
								visible: false
							})
						}
					}

					this.choujiang = uni.getStorageSync('choujiang')
					this.bid = uni.getStorageSync('bid')

					// #ifdef MP-WEIXIN
					uni.login({
						provider: 'weixin',
						timeout: 3000,
						success: res => {
							if (res.code) {
								this.bindOpenId(res.code)
							}
						},
						fail: () => {
							this.toHome()
						}
					})
					// #endif

					// #ifdef H5
					if (payurl) {
						window.location.href = payurl;
					} else {
						this.toHome()
					}
					// #endif
				} else {
					this.isLogin = true;
				}
			},
			async bindOpenId(code) {
				const res = await getPersonalCenter('s=/ApiMy/savewxopenid', {
					code: code
				}, true)
				const {
					data,
					status,
					msg
				} = res.data

				if (status == 1) {
					this.toHome()
				} else {
					this.showToast(msg);
				}
			},
			toHome() {
				setTimeout(() => {
					if (this.bid) {
						// #ifdef MP-WEIXIN
						this.isRestart = true;
						wx.restartMiniProgram({
							path: '/pages/tab/home'
						});
						// #endif

						// #ifdef H5
						uni.reLaunch({
							url: `/business/pages/business_tab/qrCodePay?bid=${this.bid}`
						})
						// #endif
					} else if (this.choujiang > 0) {
						// #ifdef MP-WEIXIN
						this.isRestart = true;
						wx.restartMiniProgram({
							path: '/pages/tab/home'
						});
						// #endif

						// #ifdef H5
						this.onSkip(`/package/mine/circleDraw?id=${this.choujiang}&pageType=1`)
						// #endif
					} else {
						// #ifdef H5
						uni.switchTab({
							url: '/pages/tab/home'
						})
						// #endif

						// #ifdef MP-WEIXIN
						this.isRestart = true;
						wx.restartMiniProgram({
							path: '/pages/tab/home'
						});
						// #endif

						// #ifdef APP-PLUS
						//更新完重启app
						plus.runtime.restart();
						// #endif
					}
					uni.removeStorageSync('choujiang');

				}, 1000)
			},
			onChangeBtn(i) {
				this.tabIndex = i
			},

			onClickLogin() {
				this.tabIndex == 0 ? this.onGoTable() : this.onCodeLogin()
			},
			// 验证码登录
			async onCodeLogin() {
				if (!/^1[3456789]\d{9}$/.test(this.account)) {
					this.showToast('电话号码不正确')
				} else if (!this.yzm) {
					this.showToast('验证码不能为空')
				} else if (!this.isChecked) {
					this.showToast('请先阅读并同意协议')
				} else {
					// 验证码
					this.onLogin()
				}
			},
			//密码登录
			async onGoTable() {
				if (!/^1[3456789]\d{9}$/.test(this.account)) {
					this.showToast('电话号码不正确')
				} else if (!this.password) {
					this.showToast('请输入密码')
				} else if (!this.isChecked) {
					this.showToast('请先阅读并同意协议')
				} else {
					// 登陆
					this.onLogin()
				}
			},

			//发送短信验证码
			async onGetVerificationCode() {
				if (this.isSend) {
					this.showToast('请勿重复发送验证码')
					return;
				}
				if (/^1[3456789]\d{9}$/.test(this.account)) {
					// 在验证码
					const res = await getVerificationCode('s=/ApiIndex/sendsms', {
						tel: this.account
					})
					const {
						status,
						msg
					} = res.data
					this.showToast(msg)
					if (status == 1) {
						this.isSend = true;
						const timer = setInterval((v) => {
							this.time -= 1;
							if (this.time == 0) {
								this.isSend = false;
								this.time = 60;
								clearInterval(timer);
							}
						}, 1000);
					}
				} else {
					this.showToast('请输入正确手机号')
				}
			},
			onInput() {
				this.isHide = false
			},
		},
	}
</script>

<style lang="scss" scoped>
	.passwordBigBox {
		position: relative;

		.eyeIcon {
			right: 30rpx;
			top: 20rpx;
			position: absolute;
		}
	}

	.checkBigBox {
		font-size: 26rpx;
		margin: 50rpx 0 50rpx;
	}

	.cardBtn {
		background: #EB292E;
		color: #fff;
		border-radius: 15rpx;
		margin-left: 15rpx;
		height: 90rpx;
	}

	.btnBigBox {
		padding: 30rpx 10rpx;
		font-size: 32rpx;
		color: #333333;

		.line {
			width: 60rpx;
			height: 4rpx;
			border-radius: 30%;
			margin-left: 40rpx;
			margin-top: 15rpx;
		}

		.activeColor {
			background: #41644A;
		}

		.activeText {
			color: #41644A;
		}
	}

	.submitBtn {
		margin: 50rpx 0;
		color: #fff;
		font-size: 34rpx;
		background: #41644A;
		border-radius: 14rpx;
		padding: 20rpx 0;
		justify-content: center;
	}

	.codeBox {
		display: grid;
		grid-template-columns: 60% 40%;
	}

	.loginLinkBox {
		font-size: 26rpx;
		font-weight: bold;
		margin-top: 100rpx;

		.loginLink {
			color: #FF3E1E;
		}
	}


	.forget {
		font-size: rpx(12);
		font-weight: 500;
		color: #FF3E1E;
	}

	.input {
		background: #F6F4FC;
		border-radius: 20rpx;
		height: 100rpx;
		margin-bottom: 50rpx;
		border: none;
		padding: 0 20rpx;
	}

	.loginAndRegister {
		color: #333333;
	}

	.greetText {
		font-size: 48rpx;
		font-weight: bold;
		padding: 200rpx 0 100rpx 0;
	}

	.logoBigBox {
		padding: 0 70rpx;
	}
	
	.safety {
		height: 100vh;
		background: url('https://img.2024csnl.com/static/2.x/a23.png') center bottom no-repeat #F8F8F8;
		background-size: contain;
	}

	.forgetText {
		font-size: 48rpx;
		font-weight: bold;
		padding: 100rpx 0 100rpx 44rpx;
		text {
			display: block;
			font-weight: normal;
			color: #000000;
			&:nth-child(2) {
				font-size: 28rpx;
				opacity: 0.3;
				text-transform: uppercase;
			}
		}
	}
</style>